import time
import threading
from threading import Lock


# 多线程
def sing(name):
    print(f"{name}在唱歌")
    time.sleep(2)
    print("歌唱完了")


def dance(name):
    print(f"{name}在跳舞")
    time.sleep(2)
    print("舞跳完了")


# if __name__ == '__main__':
#     t1 = threading.Thread(target=sing, args=("张三",))
#     t2 = threading.Thread(target=dance, args=("张三",))
#     # 守护线程
#     t1.daemon = True
#     t2.daemon = True
#     # 开启线程
#     t1.start()
#     t2.start()
#     # 阻塞线程
#     t1.join()
#     t2.join()
#     print(t1.name)
#     print(t2.name)
#     print("表演结束")


def task():
    time.sleep(1)
    print("当前线程是：", threading.current_thread().name)


# if __name__ == '__main__':
#     for i in range(5):
#         t = threading.Thread(target=task)
#         t.start()

# 线程共享资源
li = []


def wdata():
    for i in range(5):
        li.append(i)
        time.sleep(1)
    print("写入的数据是：", li)


def rdata():
    print("读取的数据是：", li)


# if __name__ == '__main__':
#     wd = threading.Thread(target=wdata)
#     rd = threading.Thread(target=rdata)
#     wd.start()
#     wd.join()
#     rd.start()
#     rd.join()

# 资源竞争
# a = 0
# b = 1000000
#
#
# def add():
#     for i in range(b):
#         global a
#         a += 1
#     print("第一次累加：", a)
#
#
# def add2():
#     for i in range(b):
#         global a
#         a += 1
#     print("第二次累加：", a)


# add()
# add2()
# if __name__ == '__main__':
#     a1 = threading.Thread(target=add)
#     a2 = threading.Thread(target=add2)
#     a1.start()
#     a1.join()
#     a2.start()
#     a2.join()

# 线程同步
# 1 join()
# 2 互斥锁
# 加锁 和 解锁 必须成对出现

lock = Lock()
a = 0
b = 1000000


def add():
    # 加锁
    lock.acquire()
    for i in range(b):
        global a
        a += 1
    print("第一次累加：", a)
    # 解锁
    lock.release()


def add2():
    lock.acquire()
    for i in range(b):
        global a
        a += 1
    print("第二次累加：", a)
    lock.release()


if __name__ == '__main__':
    a1 = threading.Thread(target=add)
    a2 = threading.Thread(target=add2)
    a1.start()
    a2.start()
